﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ZLCMS.Business;
using ZLCMS.Business.DwzFrame;
using ZLCMS.Data.Model;
using NHibernate;
using Senparc.Weixin.MP.Entities;
using NHibernate.Criterion;
using System.Collections.Generic;
using ZLCMS.Business.Util;
using Senparc.Weixin.MP.Helpers;

namespace ZLCMS.Web.SystemManage.Weixin
{
    public partial class EditTextMaterial : System.Web.UI.Page
    {
        protected FrameHelper _frameHelper;

        protected WxMaterial _materialDb;
        protected WxMaterialText _textDb;

        private string _uid;

        protected string _userAccount;

        protected void Page_Load(object sender, EventArgs e)
        {
            _userAccount = UserKit.GetUserAccountFailLogin();

            _frameHelper = new FrameHelper(this);

            //初始化全局变量值
            InitializeGlobalValue();
            //初始化控件值
            InitializeContent();

            if (IsPostBack)
            {
                Save();
            }
        }

        private void Save()
        {
            using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
            {
                ITransaction tran = session.BeginTransaction();

                try
                {
                    if (string.IsNullOrEmpty(_uid))//新建
                    {
                        WxMaterial materialDb = new WxMaterial();

                        materialDb.Title = tb_name.Text;
                        materialDb.MsgType = "text";
                        materialDb.CreateDate = DateTime.Now;
                        materialDb.UpdateDate = DateTime.Now;
                        materialDb.Status = "1";
                        materialDb.OwnerAccount = _userAccount;

                        //todo:变成XML
                        //materialDb.ResponseXml = CreateXml(session, tb_content.Text);

                        session.Save(materialDb);

                        WxMaterialText textDb = new WxMaterialText();
                        textDb.Content = tb_content.Text;
                        textDb.Id = materialDb.Id;
                        textDb.OwnerAccount = _userAccount;

                        session.Save(textDb);
                    }
                    else//修改
                    {
                        _materialDb.Title = tb_name.Text;
                        _textDb.Content = tb_content.Text;

                        _materialDb.ResponseXml = CreateXml(session, tb_content.Text);

                        session.Update(_materialDb);
                        session.Update(_textDb);
                    }

                    session.Flush();
                    tran.Commit();
                }
                catch (System.Exception ex)
                {
                    tran.Rollback();
                    _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                    return;
                }
            }

            _frameHelper.Alert(new ReturnCode()
            {
                statusCode = 200,
                message = "操作成功!",
                navTabId = _frameHelper.NavTabId
            });
        }

        protected void InitializeGlobalValue()
        {
            if (!IsPostBack)
            {
                ViewState["uid"] = Request["uid"];
            }
            _uid = (string)ViewState["uid"];

            if (!string.IsNullOrEmpty(_uid))
            {
                using (ISession session = DotNet.Common.NHibernateUtil.SessionFactoryHelper.CreateSession())
                {
                    try
                    {
                        if (!IsPostBack)
                        {
                            ViewState["uid"] = Request["uid"];
                        }

                        _materialDb = session.CreateCriteria<WxMaterial>().Add(Expression.Eq("Id", int.Parse(_uid))).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterial>();

                        if (_materialDb == null)
                        {
                            throw new Exception("找不到对应信息.");
                        }

                        _textDb = session.CreateCriteria<WxMaterialText>().Add(Expression.Eq("Id", _materialDb.Id)).Add(Expression.Eq("OwnerAccount", _userAccount)).UniqueResult<WxMaterialText>();

                        if (_textDb == null)
                        {
                            throw new Exception("找不到对应信息.");
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _frameHelper.Alert(new ReturnCode() { statusCode = 300, message = "操作出错-" + ex.Message });
                        return;
                    }
                }
            }
        }

        protected void InitializeContent()
        {
            //页面控件值
            if (!IsPostBack)
            {
                if (!string.IsNullOrEmpty(_uid))
                {
                    tb_name.Text = _materialDb.Title;
                    tb_content.Text = _textDb.Content;
                }
            }
        }

        protected string CreateXml(ISession session, string content)
        {
            ResponseMessageText textEn = new ResponseMessageText();

            textEn.ToUserName = "%TOUSERNAME%";
            textEn.FromUserName = "%FROMUSERNAME%";
            textEn.CreateTime = DateTime.Parse("1900-01-01 00:00:00");
            textEn.Content = content;

            return EntityHelper.ConvertEntityToXmlString<ResponseMessageText>(textEn).Replace("-2209017600", "%CREATETIME%");
        }
    }
}
